package com.qu.waibao.search;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.bean.SearchHistroy;
import com.qu.waibao.utils.ToastUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.one_TagFlowLayout)
    TagFlowLayout one_TagFlowLayout;
    @BindView(R.id.et_search)
    EditText et_search;
    private Intent intent;
    private String keywords = "";
    private DbManager.DaoConfig daoConfig;
    private DbManager db;
    private SearchHistroy searchHistroy;
    private  TagAdapter<SearchHistroy> tagAdapter;
    private List<SearchHistroy> histroys = new ArrayList<>();
    @Override
    protected int getContentView() {
        return R.layout.activity_search;
    }
    @Override
    protected void initWidget() {
        super.initWidget();
        //对数据库进行初始化
        daoConfig = new DbManager.DaoConfig()
                .setDbName("search.db")
                .setDbVersion(1)
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                });
        db = x.getDb(daoConfig);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP){
                    keywords = et_search.getText().toString().trim()+"";
                    if(!TextUtils.isEmpty(keywords)){
                        try {
                            long count = db.selector(SearchHistroy.class).count();
                            if (count == 15) {
                                //先删除最老的10条数据
                                SearchHistroy item = db.selector(SearchHistroy.class).orderBy("id").findFirst();
                                db.delete(item);
                                //在保存最新
                                searchHistroy = new SearchHistroy();
                                searchHistroy.setResult(keywords);
                                db.save(searchHistroy);
                            } else {
                                searchHistroy = new SearchHistroy();
                                searchHistroy.setResult(keywords);
                                db.save(searchHistroy);
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        et_search.setText("");
                        Intent intent = new Intent(SearchActivity.this,HomeSearchActivity.class);
                        intent.putExtra("keywords",keywords);
                        startActivity(intent);
                    }else {
                        ToastUtil.show(SearchActivity.this,"请输入搜索的关键字");
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        one_TagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if(histroys.size() > 0) {
                    intent = new Intent(SearchActivity.this, HomeSearchActivity.class);
                    intent.putExtra("keywords", histroys.get(position).getResult());
                    startActivity(intent);
                }
                return false;
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        x.task().run(new Runnable() {
            @Override
            public void run() {
                try {
                    final List<SearchHistroy> histroy = db.selector(SearchHistroy.class).orderBy("id")
                            .limit(15).findAll();
                    if(histroy != null) {
                        histroys.clear();
                        histroys.addAll(histroy);
                        x.task().post(new Runnable() {
                            @Override
                            public void run() {
                                if(histroy.size() > 0){
                                    one_TagFlowLayout.setVisibility(View.VISIBLE);
                                }
                                tagAdapter = new TagAdapter<SearchHistroy>(histroy) {
                                    @Override
                                    public View getView(FlowLayout parent, int position, SearchHistroy s) {
                                        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        lp.setMargins(20, 10, 20, 10);
                                        TextView tv = new TextView(SearchActivity.this);
                                        tv.setText(s.getResult());
                                        tv.setTextSize(12);
                                        tv.setTextColor(getResources().getColor(R.color.text_color));
                                        tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.h_tag_bg));
                                        return tv;
                                    }
                                };
                                one_TagFlowLayout.setAdapter(tagAdapter);
                            }
                        });

                    }

                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.tv_search,R.id.ll_back,R.id.tv_clear})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_search:
                keywords = et_search.getText().toString().trim();
                if(!TextUtils.isEmpty(keywords)){
                    try {
                        long count = db.selector(SearchHistroy.class).count();
                        if (count == 15) {
                            //先删除最老的10条数据
                            SearchHistroy item = db.selector(SearchHistroy.class).orderBy("id").findFirst();
                            db.delete(item);
                            //在保存最新
                            searchHistroy = new SearchHistroy();
                            searchHistroy.setResult(keywords);
                            db.save(searchHistroy);
                        } else {
                            searchHistroy = new SearchHistroy();
                            searchHistroy.setResult(keywords);
                            db.save(searchHistroy);
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    et_search.setText("");
                    Intent intent = new Intent(this,HomeSearchActivity.class);
                    intent.putExtra("keywords",keywords);
                    startActivity(intent);
                }else {
                    ToastUtil.show(this,"请输入搜索的关键字");
                }
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_clear:
                try {
                    histroys.clear();
                    db.delete(SearchHistroy.class);
                    one_TagFlowLayout.setVisibility(View.GONE);
                    ToastUtil.show(this,"删除成功");
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(db != null){
            db = null;
        }
        if(daoConfig != null){
            daoConfig = null;
        }

    }
}
